<template>
  <basic-drawer
    v-model:visible="visible"
    title="title"
    ok-text="保存配置"
    @ok="handleSubmit"
    @open="handleBeforeOpen"
    @close="handleBeforeClose">
    <a-form ref="formRef" :model="formData" layout="vertical">
      <a-form-item label="规则名称" field="name">
        <a-input v-model="formData.name"></a-input>
      </a-form-item>
      <a-form-item label="匹配规则">
        <a-table
          :data="formData.conditions"
          :columns="columns"
          :pagination="false">
          <template #field="{ record, rowIndex }">
            <WafFieldItem
              v-model="record.field"
              v-model:custom-value="record.customValue"
              :init="initTable"
              :field="record.field"
              :operator="record.operator"
              :row-index="rowIndex"
              @field-change="handleFieldChange(rowIndex)"></WafFieldItem>
          </template>
          <template #operator="{ record, rowIndex }">
            <WafOperator
              v-model="record.operator"
              :field="record.field"
              :operator="record.operator"
              :init="initTable"
              :row-index="rowIndex"
              @operator-change="
                (count) => handleOperatorChange(rowIndex, count)
              " />
          </template>
          <template #value="{ record, rowIndex }">
            <WafValueItem
              v-model="record.value"
              :init="initTable"
              :field="record.field"
              :operator="record.operator"
              :row-index="rowIndex">
            </WafValueItem>
          </template>
          <template #action="{ rowIndex }">
            <a-link
              :hoverable="false"
              status="danger"
              :disabled="formData.conditions.length < 2"
              @click="handleRuleValue('delete', rowIndex)">
              删除
            </a-link>
          </template>
          <template #footer>
            <a-button type="primary" @click="handleRuleValue('add')">
              添加一行
            </a-button>
          </template>
        </a-table>
      </a-form-item>
    </a-form>
  </basic-drawer>
</template>
<script lang="ts" setup>
import { getApiWafGetApi } from '@/apis/modules/waf'
import type { CommonReturnListItem } from '@/apis/schema/all'
import { useConfigStore } from '@/stores/config'
import { v4 as uuidV4 } from 'uuid'
import WafFieldItem from './WafFieldItem.vue'
import WafValueItem from './WafValueItem.vue'
import type { FormInstance } from '@arco-design/web-vue'

type RuleItem = {
  uuid?: string
  field: string
  operator: string
  value?: string | string[]
  customValue?: string
  custom_field?: string
  count?: number
}
const visible = defineModel<boolean>({ required: true })
const ruled = defineModel<string>('ruleId', { required: true })
const configStore = useConfigStore()
const initTable = ref(true)
const formRef = ref<FormInstance>()
const formData = ref<{
  name: string
  operator: string
  conditions: RuleItem[]
}>({
  name: '',
  operator: '',
  conditions: [
    {
      uuid: uuidV4(),
      field: 'content_type',
      operator: 'eq',
      value: undefined,
      count: undefined
    }
  ]
})

const columns = buildColumns([
  {
    title: '匹配字段',
    slotName: 'field'
  },
  {
    title: '运算符',
    width: 180,
    slotName: 'operator'
  },
  {
    title: '值',
    slotName: 'value'
  },
  {
    title: '操作',
    width: 64,
    slotName: 'action'
  }
])

type WafConditionItem = CommonReturnListItem<'/api/waf/condition/query', 'get'>
// 当前行的操作符信息
const currentItemOperatorValue = (field: string, operatorField: string) => {
  const list = configStore.conditionQuery as WafConditionItem[]
  const operations = list.find((item) => item.field?.field === field)?.operators
  return operations?.find((item) => item.field === operatorField)?.value
}
// 添加或删除规则
const handleRuleValue = (type: 'delete' | 'add', rowIndex?: number) => {
  if (type === 'delete') {
    formData.value.conditions.splice(rowIndex!, 1)
  } else {
    formData.value.conditions.push({
      uuid: uuidV4(),
      field: 'content_type',
      operator: 'eq',
      value: undefined
    })
  }
}

// 改变匹配字段重置操作符和值
const handleFieldChange = (index: number) => {
  formData.value.conditions[index].operator = 'eq'
  formData.value.conditions[index].value = undefined
}
// 改变操作符重置值
const handleOperatorChange = (index: number, count?: number) => {
  formData.value.conditions[index].value = undefined
  formData.value.conditions[index].count = count
}
const handleSubmit = async () => {
  const error = await formRef.value?.validate()

  formData.value.conditions = formData.value.conditions.map((item) => {
    if (item.count === 0) {
      return {
        ...item,
        value: []
      }
    } else {
      const result = Array.isArray(item.value) ? item.value : [item.value ?? '']
      return {
        ...item,
        value: result.filter(Boolean)
      }
    }
  })
  console.log(formData.value)
  visible.value = false
  if (error) return
}
const handleBeforeOpen = () => {
  getData()
}
const handleBeforeClose = () => {}

const getData = () => {
  if (ruled.value) {
    getApiWafGetApi({ id: ruled.value }).then((res) => {
      const conditions = res.conditions
      const list =
        conditions?.map((condition) => ({
          field: condition.field!,
          operator: condition.operator!,
          value: condition.value!,
          customValue: condition.custom_field ?? ''
        })) ?? []
      formData.value.conditions = list.map((item) => {
        const a = currentItemOperatorValue(item.field, item.operator)!
        const value = (a?.count ?? 1) > 1 ? item.value : item.value.join()
        return {
          ...item,
          value
        }
      })
      initTable.value = false
    })
  }
}
</script>
<style lang="less" scoped>
.arco-table {
  :deep(tbody) {
    .arco-table-td {
      vertical-align: baseline;
    }
  }
}
</style>
